package com.shengdong.water.feature.management.monitor

import android.content.res.Configuration
import android.text.TextUtils
import android.util.Log
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.lifecycle.lifecycleScope
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.hjq.toast.Toaster
import com.kongzue.dialogx.dialogs.WaitDialog
import com.shengdong.water.R
import com.shengdong.water.base.BaseVMActivity
import com.shengdong.water.code.base.BaseActivity
import com.shengdong.water.code.config.RouterConfig
import com.shengdong.water.code.viewmodel.VideoMonitorViewModel
import com.shengdong.water.databinding.ActivityVideoPlayerBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.util.regex.Pattern

@Route(path = RouterConfig.Management.VIDEO_PLAYER_PATH)
@AndroidEntryPoint
class VideoPlayerActivity : BaseVMActivity<ActivityVideoPlayerBinding, VideoMonitorViewModel>() {

    override fun getLayoutId() = R.layout.activity_video_player
    override fun getViewModelClass() = VideoMonitorViewModel::class.java
    private var player: ExoPlayer? = null
    private var videoUrl: String? = null
    private var cameraIndexCode: String? = null


    override fun initViews() {
        super.initViews()
        setTitle("视频监控")
        binding.viewModel = viewModel
        player = ExoPlayer.Builder(this).build()
        videoUrl = intent.getStringExtra("videoUrl")
        cameraIndexCode = intent.getStringExtra("videoCam")
//        setupPlayer()
    }

    override fun initData() {
        super.initData()
        viewModel.getVideoCameraUrl(cameraIndexCode!!)

    }

    override fun showLoading(loading: String) {
        WaitDialog.show("视频$loading")
    }

    override fun dismissLoading() {
        WaitDialog.dismiss()
    }

    override fun observeData(){
        super.observeData()
        lifecycleScope.launch {
            viewModel.cameraUrl.collect {
                val regex = "url=([^}]+)" // 匹配 "url=" 后面的任何非 "}" 字符
                val pattern = Pattern.compile(regex)
                val matcher = pattern.matcher(it.toString())
                if (matcher.find()) {
                    videoUrl = matcher.group(1) // group(1) 是第一个捕获组的内容
                    Log.d("VideoPlayerActivity", "匹配到的URL: $videoUrl")
                    if(TextUtils.isEmpty(videoUrl)){
                        Toaster.show("无效的视频链接")
                       return@collect
                    }
                    setupPlayer()
                }
            }
        }
    }

    private fun setupPlayer() {
        player.also { exoPlayer ->
            binding.playerView.player = exoPlayer

            // 设置视频源（这里用示例URL，请替换成你的视频URL）
            val mediaItem = MediaItem.fromUri(videoUrl?:"")
            exoPlayer?.setMediaItem(mediaItem)
            // 设置播放器监听
            exoPlayer?.addListener(object : Player.Listener {
                override fun onPlaybackStateChanged(state: Int) {
                    when (state) {
                        Player.STATE_BUFFERING -> {
                            // 处理缓冲状态
                        }
                        Player.STATE_READY -> {
                            // 视频准备就绪
                            dismissLoading()
                        }
                        Player.STATE_ENDED -> {
                            // 播放结束
                        }
                        Player.STATE_IDLE -> {
                            // 播放器空闲
                        }
                    }
                }
            })

            // 准备播放器
            exoPlayer?.prepare()
        }
    }

    override fun onResume() {
        super.onResume()
        player?.play()
    }

    override fun onPause() {
        super.onPause()
        player?.pause()
    }

    override fun onDestroy() {
        super.onDestroy()
        player?.release()
        player = null
    }

    override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        val orientation = newConfig.orientation

        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            // 横屏全屏
            enterFullscreen()
        } else {
            exitFullscreen()
        }
    }

    private fun enterFullscreen() {
        WindowCompat.setDecorFitsSystemWindows(window, false)
        WindowInsetsControllerCompat(window, binding.playerView).let { controller ->
            controller.hide(WindowInsetsCompat.Type.systemBars())
            controller.systemBarsBehavior =
                WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
        }
    }

    private fun exitFullscreen() {
        WindowCompat.setDecorFitsSystemWindows(window, true)
        WindowInsetsControllerCompat(window, binding.playerView).show(WindowInsetsCompat.Type.systemBars())
    }


}